package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.uu.view.District;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseAdapter;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnBookProductionAdapter;
import com.hemaapp.yjnh.adapter.CmnProductionAdapter;
import com.hemaapp.yjnh.listener.OnBlogItemClickListener;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.Blog;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 带有地区的商品列表，包括预约类和实体类的商品
 * 乐乐中的本地、周边、热门景点、超值抢购中的商品
 * 地标中的地区商品也复用本界面
 *
 * @author GuiyouZhang
 *         Date：2016年1月7日 下午6:12:48
 *         Email:guiyouzhang@163.com
 */
public class CmnProductionListWithDistrictActivity extends BaseActivity implements OnClickListener {

    @Bind(R.id.btn_back)
    ImageButton btnBack;
    @Bind(R.id.ed_search)
    EditText edSearch;
    @Bind(R.id.btn_map)
    ImageButton btnMap;
    @Bind(R.id.layout_cities)
    LinearLayout layoutCities;
    @Bind(R.id.layout_around)
    HorizontalScrollView layoutAround;
    @Bind(R.id.tv_default)
    TextView tvDefault;
    @Bind(R.id.layout_default)
    LinearLayout layoutDefault;
    @Bind(R.id.layout_price)
    LinearLayout layoutPrice;
    @Bind(R.id.layout_sales)
    LinearLayout layoutSales;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;

    private ArrayList<Blog> mBlogs = new ArrayList<>();//推荐商品
    private ArrayList<District> allDistricts = new ArrayList<District>();//周边的地级市
    private BaseAdapter adapter;
    //用于获取网络数据的参数
    private String keytype = "8";//类型	1:粮票超值;    2:有机商品    3:田家商品    4:地标商品    5:村游商品    6:唠嗑帖子
    //7:农货日志    8:粮库商品    9:乐乐商品    10:走走相关    11:特产商品    12:苗木    13:花卉    14:家电    15:日用品
    //16:粮库商家商品    17:农需商品
    private String keyid = "无";
    private String orderby = "1";//1：智能排序    2：热销    3：好评    4：唠嗑排序    5：时间排序    6：价格排序
    private String ordertype = "1";//1:降序；2:升序
    private String keyword = "";//搜索关键字	可选传参数，需要时传递;keytype=3时传商品类型名称
    private String saleflag = "";//农货状态	只有keytype=3时需要传递该参数；0：关闭；1：进行中
    private String topflag	 = "";//推荐/热门景点标志	topflag=1，可选传参数，keytype=2,3,4,8,9，16时可传
    private String cheapflag = "";//低价抢购标志	cheapflag=1，可选传参数，只有keytype=9时可传
    private String score_percent = "";//粮票占比	5-9的整数，可选传参数，只有keytype=8时可传
    private String seller_id = "";//卖家id	可选传参数，keyytype=4,5,9,10,11可传
    private String lng = "";//可选传参数，需要时传递
    private String lat = "";//纬度	可选传参数，需要时传递
    private String  district_name = "";//地区	可选传参数，用于获取周边农需商品
    private int page = 0;
    private String provinceId = "";//地级市所在的省份名称,用于获取周边的地市
    //显示周边的地区
    private TextView[] textViews;
    private String[] huabei = {"北京", "天津", "河北", "山西", "内蒙古"};
    private String[] dongbei = {"辽宁", "吉林", "黑龙江"};
    private String[] huadong = {"上海", "江苏", "浙江", "安徽", "福建", "江西", "山东"};
    private String[] huanan = {"广东", "广西", "海南", "台湾", "香港", "澳门"};
    private String[] huazhong = {"河南", "湖南", "湖北"};
    private String[] xinan = {"重庆", "四川", "贵州", "云南", "西藏"};
    private String[] xibei = {"陕西", "甘肃", "青海", "宁夏", "新疆"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_production_list_with_district);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        lat = XtomSharedPreferencesUtil.get(mContext, "lat");
        lng = XtomSharedPreferencesUtil.get(mContext, "lng");
        init();
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        keytype = mIntent.getStringExtra("keytype");
        keyid = mIntent.getStringExtra("keyid");
        keyword = mIntent.getStringExtra("keyword");
        saleflag = mIntent.getStringExtra("saleflag");
        topflag = mIntent.getStringExtra("topflag");
        cheapflag = mIntent.getStringExtra("cheapflag");
        score_percent = mIntent.getStringExtra("score_percent");
        seller_id = mIntent.getStringExtra("seller_id");
        district_name = mIntent.getStringExtra("district_name");

        provinceId = mIntent.getStringExtra("provinceId");
    }

    @Override
    protected void setListener() {
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().blogList(keytype, keyid, orderby, ordertype, keyword,
                        saleflag, topflag, cheapflag, score_percent, seller_id, lng, lat, district_name, "", page+"");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().blogList(keytype, keyid, orderby, ordertype, keyword,
                        saleflag, topflag, cheapflag, score_percent, seller_id, lng, lat, district_name, "", page+"");
            }
        });
        edSearch.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = v.getText().toString();
                    if (isNull(keyword)) {
                        return true;
                    }
                    mInputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                    return true;
                }
                return false;
            }
        });
    }

    private void init() {
        if (!isNull(provinceId)) {//如果是周边乐乐，需要获取周边的城市。
            getNetWorker().districtList(provinceId);
            layoutAround.setVisibility(View.VISIBLE);
        }
        if (keytype.equals("4")) {
            btnMap.setVisibility(View.GONE);
            layoutAround.setVisibility(View.VISIBLE);
            //1、华东地区（山东、江苏、安徽、浙江、福建、江西、上海）；
            //2、华南地区（广东、广西、海南）；
            //3、华中地区（湖北、湖南、河南）；
            //4、华北地区（北京、天津、河北、山西、内蒙古）；
            //5、西北地区（宁夏、新疆、青海、陕西、甘肃）；
            //6、西南地区（四川、云南、贵州、西藏、重庆）；
            //7、东北地区（辽宁、吉林、黑龙江）；
            //8、台港澳地区（台湾、香港、澳门）。
            District all = new District();
            all.setName("全部");
            allDistricts.add(all);
            if (keyid.equals("东北")) {
                for (int i = 0; i < dongbei.length; i++) {
                    District district = new District();
                    district.setName(dongbei[i]);
                    allDistricts.add(district);
                }
            } else if (keyid.equals("华东")) {
                for (int i = 0; i < huadong.length; i++) {
                    District district = new District();
                    district.setName(huadong[i]);
                    allDistricts.add(district);
                }
            } else if (keyid.equals("华南")) {
                for (int i = 0; i < huanan.length; i++) {
                    District district = new District();
                    district.setName(huanan[i]);
                    allDistricts.add(district);
                }
            } else if (keyid.equals("华北")) {
                for (int i = 0; i < huabei.length; i++) {
                    District district = new District();
                    district.setName(huabei[i]);
                    allDistricts.add(district);
                }
            } else if (keyid.equals("西北")) {
                for (int i = 0; i < xibei.length; i++) {
                    District district = new District();
                    district.setName(xibei[i]);
                    allDistricts.add(district);
                }
            } else if (keyid.equals("西南")) {
                for (int i = 0; i < xinan.length; i++) {
                    District district = new District();
                    district.setName(xinan[i]);
                    allDistricts.add(district);
                }
            } else if (keyid.equals("华中")) {
                for (int i = 0; i < huazhong.length; i++) {
                    District district = new District();
                    district.setName(huazhong[i]);
                    allDistricts.add(district);
                }
            }
            setCities();
        } else
            btnMap.setVisibility(View.VISIBLE);
        refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case DISTRICT_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case DISTRICT_LIST:
                cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                String page = netTask.getParams().get("page");
                @SuppressWarnings("unchecked")
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                ArrayList<Blog> blogs = bResult.getObjects();
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    mBlogs.clear();
                    mBlogs.addAll(blogs);
                } else {
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (blogs.size() > 0)
                        this.mBlogs.addAll(blogs);
                    else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                if (keytype.equals("4")) {
                    refreshDatas(-1);
                } else {//乐乐商品使用自己的适配器
                    refreshLeleDatas(-1);
                }
                break;
            case DISTRICT_LIST:
                @SuppressWarnings("unchecked")
                HemaPageArrayResult<District> dResult = (HemaPageArrayResult<District>) baseResult;
                if (dResult == null || dResult.getObjects() == null) {
                    return;
                }
                allDistricts.clear();
                District all = new District();
                all.setName("全部");
                allDistricts.add(all);
                allDistricts.addAll(dResult.getObjects());
                setCities();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                if (page == 0) {
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，" + baseResult.getMsg());
                break;
            case DISTRICT_LIST:
                XtomToastUtil.showShortToast(mContext, "获取周边城市失败，" + baseResult.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                if (page == 0) {
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                if (keytype.equals("4")) {
                    refreshDatas(failedType);
                } else {//乐乐商品使用自己的适配器
                    refreshLeleDatas(failedType);
                }
                break;
            case DISTRICT_LIST:
                XtomToastUtil.showShortToast(mContext, "获取周边城市失败，请稍后再试");
                break;
        }
    }

    private void refreshDatas(int failedType) {
        if (null == adapter) {
            adapter = new CmnProductionAdapter(mContext, mBlogs);
            ((CmnProductionAdapter)adapter).setItemClickListener(new OnBlogItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(mContext, CmnProductionDetailActivity.class);
                    it.putExtra("blog_id", mBlogs.get(position).getId());
                    mContext.startActivity(it);
                }

                @Override
                public void onCartListener(final int position) {
//                    Intent it = new Intent(mContext, CmnProductionDetailActivity.class);
//                    it.putExtra("blog_id", mBlogs.get(position).getId());
//                    mContext.startActivity(it);
                }
            });
            adapter.setEmptyString("暂无商品");
            listview.setAdapter(adapter);
        } else {
            adapter.setEmptyString("暂无商品");
            adapter.notifyDataSetChanged();
        }
        adapter.setFailtype(failedType);
    }

    private void refreshLeleDatas(int failedType) {
        if (null == adapter) {
            adapter = new CmnBookProductionAdapter(mContext, mBlogs);
            adapter.setEmptyString("暂时没有商品");
            ((CmnBookProductionAdapter)adapter).setClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(mContext, BookProductionDetailActivity.class);
                    it.putExtra("blog_id", mBlogs.get(position).getId());
                    startActivity(it);
                }
            });
            listview.setAdapter(adapter);
        }else {
            adapter.setEmptyString("暂时没有商品");
            adapter.notifyDataSetChanged();
        }
        adapter.setFailtype(failedType);
    }

    private void setCities() {
        // 动态添加多个城市
        if (layoutCities.getChildCount() != 0) {
            layoutCities.removeAllViews();
        }
        textViews = new TextView[allDistricts.size()];
        for (int i = 0; i < allDistricts.size(); i++) {
            RelativeLayout layout = new RelativeLayout(mContext);
            textViews[i] = new TextView(mContext);
            textViews[i].setId(i);// 动态分配id
            textViews[i].setTextSize(15);
            if (i == 0) {
                textViews[i].setTextColor(getResources().getColor(R.color.theme_orange));
            } else
                textViews[i].setTextColor(getResources().getColor(R.color.text_color_dark_grey));
            if (i < allDistricts.size() - 1) {// 在每两个城市之间加一个点
                textViews[i].setText("  " + allDistricts.get(i).getName() + "  ·");
            } else if (i == allDistricts.size() - 1) {
                textViews[i].setText("  " + allDistricts.get(i).getName());
            }
            textViews[i].setTag(allDistricts.get(i).getName());
            textViews[i].setOnClickListener(clickListener);
            layoutCities.setGravity(Gravity.CENTER);
            layoutCities.addView(textViews[i]);
        }
    }

    OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int i = v.getId();
            for (int j = 0; j < textViews.length; j++) {
                if (j == i) {
                    textViews[j].setTextColor(getResources().getColor(R.color.theme_orange));
                } else {
                    textViews[j].setTextColor(getResources().getColor(R.color.text_color_dark_grey));
                }
            }
            String name = (String) v.getTag();
            if (!isNull(name)) {
                if (name.equals("全部")) {
                    keyid = mIntent.getStringExtra("keyid");
                } else
                    keyid = name;
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
            }
        }
    };

    @OnClick({R.id.btn_back, R.id.btn_map, R.id.layout_default, R.id.layout_price, R.id.layout_sales})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_map:
                Intent itMap = new Intent(mContext, MapActivity.class);
                itMap.putExtra("city", keyid);
                startActivity(itMap);
                break;
            case R.id.layout_default:
                if (orderby.equals("1")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutDefault.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "1";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_price:
                if (orderby.equals("6")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutPrice.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutDefault.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "6";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_sales:
                if (orderby.equals("2")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutSales.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutDefault.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "2";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
        }
    }
}
